import json
from aide.UserAide import User
from flask_login import login_user, logout_user, current_user
from flask import render_template, redirect, request


class UserController:
    def login(self):
        if request.method == 'POST':
            account = request.form.get('account')
            passwd = request.form.get('passwd')
            cur = User(0)
            cur.set_attribute(account)
            if not cur.attr:
                return json.dumps({'error': 1, 'message': '用户或密码错误'})
            if cur.attr['passwd'] != passwd:
                return json.dumps({'error': 1, 'message': '用户或密码错误'})
            # 通过Flask-Login的login_user方法登录用户
            login_user(User(cur.attr['id']))
            return json.dumps({'error': 0, 'message': '登录成功'})
        if current_user.is_authenticated:
            return redirect('/')
        return render_template('login.html')

    def logout(self):
        logout_user()
        return redirect('/')
